package cn.edu.csmzxy.rk233x.auth_system.controller;

/**
 * @author wumxing
 * @date 2025/10/15 9:52
 * @description
 */
import cn.edu.csmzxy.rk233x.auth_system.dto.LoginDTO;
import cn.edu.csmzxy.rk233x.auth_system.dto.ResultDTO;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysPermission;
import cn.edu.csmzxy.rk233x.auth_system.service.SysPermissionService;
import cn.edu.csmzxy.rk233x.auth_system.util.JwtUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "认证接口", description = "用户登录、Token刷新等接口")
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    private JwtUtil jwtUtil;
    @Operation(summary = "用户登录", description = "输入用户名和密码，登录成功返回JWT Token")
    @PostMapping("/login")
    public ResultDTO<Map<String, String>> login(
            @Parameter(description = "登录请求参数（用户名+密码）", required = true)
            @Valid @RequestBody LoginDTO loginDTO) {
        // 1. 构建认证Token（用户名+密码）
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                loginDTO.getUsername(), loginDTO.getPassword()
        );
        // 2. 调用AuthenticationManager进行认证（触发UserDetailsService查询用户）
        Authentication authentication = authenticationManager.authenticate(authToken);
        // 3. 存入SecurityContext（可选，JWT过滤器会重新解析）
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 4. 生成JWT Token
        String token = jwtUtil.generateToken(loginDTO.getUsername());
        // 5. 获取权限菜单
        List<String> authorities =  authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();
        List<SysPermission> permissions = sysPermissionService.selectPermissionTree();
        // 5. 封装响应数据
        Map<String, String> data = new HashMap<>();
        data.put("token", token);
        data.put("username", loginDTO.getUsername());
        data.put("tokenHead", "Bearer ");  // 告知前端Token前缀
        data.put("roles",JSON.toJSONString(authorities.stream().filter(p->p.contains("ROLE_")).toList()));
        data.put("menuList", JSON.toJSONString(permissions));
        data.put("authorities",JSON.toJSONString(authorities.stream().filter(p->!p.contains("ROLE_")).toList()));
        return ResultDTO.success(data);
    }
}